package com.sparrow.common.uuid;

import com.google.common.base.Preconditions;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 基于服务器id前缀 + 自增id
 */
@Component
public class UUIDService {

    private final static long BEGIN_DEFAULT = 10000000000L;
    /**
     * 服务器id 映射最大id
     */
    private Map<Integer, AtomicInteger> serverMaxId = new ConcurrentHashMap<>();

    public void setServerMaxId(int server, long maxId) {
        int index = (int) (maxId % BEGIN_DEFAULT);
        serverMaxId.put(server, new AtomicInteger(index));
    }

    public long nextId(int serverId) {
        AtomicInteger roleCounter = serverMaxId.get(serverId);
        return serverId * BEGIN_DEFAULT + roleCounter.incrementAndGet();
    }

    public long getMaxId(int serverId) {
        AtomicInteger counter = serverMaxId.get(serverId);
        Preconditions.checkNotNull(counter);
        return counter.get();
    }

}
